package com.zwl.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zwl.po.DeptPo;
import com.zwl.po.PageBean;
import com.zwl.po.RolePo;
import com.zwl.po.UserDetailPo;
import com.zwl.po.UserPo;
import com.zwl.service.DeptService;
import com.zwl.service.RoleService;
import com.zwl.service.UserService;
import com.zwl.service.impl.DeptServiceImpl;
import com.zwl.service.impl.RoleServiceImpl;
import com.zwl.service.impl.UserServiceImpl;
import com.zwl.utils.ConstantUtils;
import com.zwl.utils.StringUtils;

public class UserServlet extends BaseServlet {
	private UserService userService=new UserServiceImpl();
	private DeptService deptService=new DeptServiceImpl();
	private RoleService roleService=new RoleServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String opr=req.getParameter("opr");
		
		if("loadData".equals(opr)){
			loadData(req, resp);
		}else if("add".equals(opr) || "update".equals(opr)){
			int rows=0;
			String msg="";
			try {
				UserPo saveEntity=getEntity(req);
				if("update".equals(opr)){
					rows=userService.updateUser(saveEntity);
				}else{
					Integer[] results=userService.saveUser(saveEntity);
					rows=results[0];
					int primaryKey=results[1];
					System.out.println("primaryKey:"+primaryKey);
				}
			} catch (Exception e) {
				e.printStackTrace();
				msg="Save failed, Please try again!"+e.getMessage();
			}
			PrintWriter out=resp.getWriter();
			if(rows>0){
				out.println("<script type='text/javascript'>alert('Save successfully!');location.href='userServlet';</script>");
			}else{
				out.println("<script type='text/javascript'>alert('"+msg+"');history.back();</script>");
			}
		}else{
			List<UserPo> list=userService.findByCondition(null);
			req.setAttribute("list", list);
			Integer pageIndex=StringUtils.str2Integer(req.getParameter("pageIndex"), false, 1);
			PageBean<UserDetailPo> pageBean=userService.findPageByCondition(pageIndex, ConstantUtils.PAGE_SIZE, null);
			req.setAttribute("pageBean", pageBean);
			req.getRequestDispatcher("user_list.jsp").forward(req, resp);
		}
	}

	private UserPo getEntity(HttpServletRequest req) throws IOException {
		UserPo saveEntity=null;
		java.sql.Timestamp currTime=new java.sql.Timestamp(System.currentTimeMillis());
		UserPo currUser=this.getCurrUser(req.getSession());
		Integer userId=StringUtils.str2Integer(req.getParameter("userId"), false, null);
		if(userId!=null){
			saveEntity=userService.findbyId(userId);
		}else{
			saveEntity=new UserPo();
			saveEntity.setUserDetail(new UserDetailPo());
			saveEntity.setIsActive(1);
			saveEntity.setCreatedId(currUser.getId());
			saveEntity.setCreatedTime(currTime);
			Properties props=new Properties();
			InputStream is=this.getClass().getClassLoader().getResourceAsStream("setup.properties");//�ӹ��̵�srcĿ¼����setup.properties�ļ�
			props.load(is);
			saveEntity.setPassword(props.getProperty("user.init.password"));
		}
		
		saveEntity.getUserDetail().setDeptId(StringUtils.str2Integer(req.getParameter("deptId"), false,null));
		saveEntity.setLoginName(req.getParameter("loginName"));
		saveEntity.getUserDetail().setName(req.getParameter("name"));
		saveEntity.getUserDetail().setSex(req.getParameter("sex"));
		saveEntity.getUserDetail().setTelephone(req.getParameter("telephone"));
		saveEntity.getUserDetail().setEmail(req.getParameter("email"));
		saveEntity.getUserDetail().setRemark(req.getParameter("remark"));
		
		String[] roleIds=req.getParameterValues("rightRoleIdList");
		if(roleIds!=null && roleIds.length>0){
			List<RolePo> roleList=new ArrayList<RolePo>();
			for(String str:roleIds){
				Integer roleId=StringUtils.str2Integer(str, false,null);
				if(roleId!=null){
					roleList.add(new RolePo(roleId));
				}
			}
			saveEntity.setRoleList(roleList);
		}
		
		saveEntity.setUpdatedId(currUser.getId());
		saveEntity.setUpdatedTime(currTime);
		
		return saveEntity;
	}

	private void loadData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Integer userId=StringUtils.str2Integer(req.getParameter("userId"), false, null);
		if(userId!=null){
			UserPo user=userService.findbyId(userId);
			req.setAttribute("user", user);
			
			
			Map<String, Object> roleMap=new HashMap<String, Object>();
			roleMap.put("isActive", 1);
			roleMap.put("exincludeUserId", userId);
			List<RolePo> leftRoleIdList=roleService.findByCondition(roleMap);
			roleMap.clear();
			roleMap.put("isActive", 1);
			roleMap.put("includeUserId", userId);
			List<RolePo> rightRoleIdList=roleService.findByCondition(roleMap);
			
			req.setAttribute("leftRoleIdList", leftRoleIdList);
			req.setAttribute("rightRoleIdList", rightRoleIdList);
		}
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("isActive", 1);
		List<DeptPo> deptList=deptService.findByCondition(map);
		req.setAttribute("deptList", deptList);
		
		req.getRequestDispatcher("user_save.jsp").forward(req, resp);
	}
}
